package com.example.sys.wx.controller;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RequestMapping("wx")
@RestController
public class WechatOpenController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private WxMpService wxMpService;

    @Resource
    private WxMpMessageRouter wxMpMessageRouter;

    @GetMapping
    public String callback(@RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("signature") String signature,
                           @RequestParam(name = "echostr", required = false) String echostr) {
        if (this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "error";
    }

    @PostMapping
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("openid") String openid,
                           @RequestParam(name = "encrypt_type", required = false) String encType,
                           @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                timestamp, nonce, msgSignature);
        //logger.info("\n消息解密后内容为：\n[{}] ", inMessage.toString());
        WxMpXmlOutMessage outMessage = this.wxMpMessageRouter.route(inMessage);
        if (outMessage == null) {
            return "";
        }
        return outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
    }
}
